#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "linuxlist.h"

#define MAX_LIST 3

typedef struct TEST
{
	int num;
	struct list_head head;
} TEST;

TEST *listHead = NULL;

void InitList(TEST *myList)
{
	myList->num = 0;
	INIT_LIST_HEAD(&(myList->head));
}

#if 1
//获得链表大小
static int GetListSize(struct list_head *head)
{
	if (NULL == head)
		return (-1);

	int i = 0;
	struct list_head *pos = NULL;

	list_for_each(pos, head)
	{
		i++;
	}
	return i;
}
#endif
#if 1
//删除节点
static int DeleteList(struct list_head *delList)
{
	if (NULL == delList)
		return -1;

	list_del(delList);

	return 0;
}
#endif

//插入节点
static int InsertList(struct list_head *newer)
{
	if (NULL == newer || NULL == listHead)
		return -1;

	struct list_head *pos = &(listHead->head);

#if 1
	if (GetListSize(pos) >= MAX_LIST)
	{
		TEST *tmp = NULL;

		tmp = container_of((listHead->head.next), TEST, head);
		listHead = tmp;

		DeleteList(pos);
	}
#endif

#if 0
	if(NULL == listHead)
	{
		listHead = newList;
		InitList(listHead);
	}
#endif

	list_add_tail(newer, &(listHead->head));

	return 0;
}

#if 1
//打印链表
static int PrintList(TEST *listHead)
{
	if (NULL == listHead)
		return -1;

	int i = 0;
	TEST *tmp = NULL;
	struct list_head *pos = NULL;

	list_for_each(pos, &(listHead->head))
	{
		tmp = container_of(pos, TEST, head);
		printf("num = %d\r\n", tmp->num);
		i++;
	}

	return 0;
}

static int DropList()
{
}

#endif

int linuxlist_test(void)
{
	if (MAX_LIST == 0)
		return (-1);

	listHead = (TEST *)calloc(sizeof(TEST), 1);

	InitList(listHead);

	int ret = -1;

	//循环创建链表
	for (int i = 0; i < 10; i++)
	{
		TEST *newList = NULL;
		newList = (TEST *)calloc(sizeof(TEST), 1);

		newList->num = i;

		ret = InsertList(&(newList->head));
		if (ret != 0)
			break;
	}

	PrintList(listHead);

	return 0;
}
